package com.hwua.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 目的：帮助获取数据库连接
 * @author Administrator
 */
public class ConnectionTools {
    private static Connection connection;
    private static String driver;
    private static String url;
    private static String user;
    private static String pwd;
    private static final Properties properties;


    static{
        //--1.实例化properties对象
        properties = new Properties();
        //--2.加载配置文件
        try {
            properties.load(ConnectionTools.class.getClassLoader().getResourceAsStream("config/db_config.properties"));
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            pwd = properties.getProperty("pwd");
        } catch (IOException e) {
            System.out.println("加载配置文件失败！");
        }
    }

    /**
     * @return
     */

    public static Connection getConnection(){
        if(connection==null){
            try {
                Class.forName(driver);
                connection = DriverManager.getConnection(url,user,pwd);
            } catch (SQLException e) {
                System.out.println("加载数据库驱动失败！");
            } catch (ClassNotFoundException e) {
                System.out.println("打开数据库连接失败！");
            }
        }
        return connection;
    }
}
